/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.web.util;

import com.garagesale.web.form.Selectable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author christophe
 */
public class FormUtils
{

    public static boolean ensureExistence(String value, String valueName, ActionErrors errors)
    {
        if (null == value || value.trim().length() == 0)
        {
            errors.add(valueName, new ActionMessage("Missing Value", valueName));
        }

        return true;
    }

    public static boolean ensureNonZeroExistence(Number value, String valueName, ActionErrors errors)
    {
        if (null == value || value.longValue() == 0)
        {
            errors.add(valueName, new ActionMessage("Missing Value", valueName));
        }

        return true;
    }

    public static List<Selectable> toSelectable(List<?> objects, Class<?> classType, String displayValueGetter, String valueGetter)
    {
        try
        {
            List<Selectable> results = new ArrayList<Selectable>();

            Method displayGetterMethod = classType.getMethod(displayValueGetter);
            Method valueGetterMethod = classType.getMethod(valueGetter);

            Object display;
            Object value;

            for (Object o : objects)
            {
                display = displayGetterMethod.invoke(o);
                value = valueGetterMethod.invoke(o);

                results.add(new Selectable(display != null ? display.toString() : "", value != null ? value.toString() : ""));

            }

            return results;

        } catch (Exception e)
        {
            // ugly and dangerous, but will do for now
            throw new RuntimeException(e);
        }

    }

    /**
     *
     * Current just returns an empty list
     * */
    public static List<String> getMessages(HttpServletRequest request)
    {
        List<String> messages = new ArrayList<String>();

        if (null != request.getAttribute(Globals.ERROR_KEY))
        {
            ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);

            Iterator iter = errors.properties();


        }
        return messages;
    }

    public static boolean hasErrorMessages(HttpServletRequest request)
    {
        if (null != request.getAttribute(Globals.ERROR_KEY))
        {
            ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);

            return !errors.isEmpty();

        }
        return false;
    }
}
